import { getTalkingByUserIDBack, userSend } from '@/services/conversation';
import { colorStr, getQueryParams } from '@/utils/utils';
import { useWebSocket } from 'ahooks';
import { Avatar, Button, Input, message, Modal } from 'antd';
import Picker from 'emoji-picker-react';
import moment from 'moment';
import { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import styles from './index.less';

interface Props {
  color: string;
  business: any;
  visible: boolean;
  receiveId: any;
  acceptid?: string;
  onCancel: () => void;
}

const Conversation: React.FC<Props> = ({ color, visible, onCancel, business, receiveId }) => {
  const { TextArea } = Input;
  const qs = getQueryParams();
  const [inputValue, setInputValue] = useState<string>('');
  const [test, setTest] = useState<number>(0);
  const [emojiModal, setEmojiModal] = useState<boolean>(false);
  const [rightSent, setRightSent] = useState<any[]>([]);

  // const { readyState, sendMessage, latestMessage } = useWebSocket(
  const { sendMessage, latestMessage } = useWebSocket(`ws://localhost:3001/?userId=${qs.id}`, {
    onOpen: () => {
      console.log('连接成功');
    },
    onClose: () => {
      onCancel();
      console.log('关闭成功');
    },
  });

  const getTalkingByUserID = useCallback(async () => {
    await getTalkingByUserIDBack({ userId: qs.id, saleId: receiveId }).then((res) => {
      setRightSent(res);
      setTest(res.length);
    });
  }, [qs.id, receiveId]);

  useEffect(() => {
    getTalkingByUserID();
  }, [getTalkingByUserID]);

  const send = () => {
    {
      sendMessage &&
        sendMessage(
          JSON.stringify({
            userId: receiveId,
            message: `${qs.id}给${receiveId}发送了${inputValue}`,
          }),
        );
    }
  };
  useEffect(() => {
    if (latestMessage !== undefined) {
      getTalkingByUserID();
    }
  }, [getTalkingByUserID, latestMessage]);

  const preventBubble = function (e: any) {
    e.preventDefault();
  };
  const onEmojiClick = (event: any) => {
    setInputValue(`${inputValue}${event.emoji}`);
    setEmojiModal(false);
  };

  const sendBtn = async () => {
    if (inputValue != '') {
      if (qs.disable === '1' || qs.disable === '3') {
        message.error('由于您的不当发言，您已被禁止通话！');
      } else {
        send();
        await userSend({ saleId: receiveId, userId: qs.id, userTalking: inputValue }).then(() => {
          getTalkingByUserID();
          setInputValue('');
        });
      }
    } else {
      message.error('请输入消息');
    }
  };

  const scrollToBottom = () => {
    document.getElementById('box')?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [test]);

  const onChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    let value = e.target.value;
    setInputValue(value);
  };

  return (
    <Modal
      title={`和${business.nickname}的聊天`}
      className={styles.container}
      open={visible}
      onCancel={onCancel}
      width={qs.role === '3' ? 680 : 888}
      footer={[]}
    >
      <div className={styles.talkWindow}>
        <div className={styles.leftBox}>
          {emojiModal && (
            <div className={styles.emojiModal}>
              <Picker onEmojiClick={onEmojiClick} />
            </div>
          )}
          <div className={styles.recording}>
            {rightSent.map((item: any) => (
              <div
                key={item.id}
                className={item.userTalking === '' ? styles.leftSent : styles.rightSent}
              >
                {item.userTalking !== '' ? (
                  <Avatar
                    size={40}
                    style={{
                      margin: '0 8px',
                      background: `${qs.avatar}`,
                      cursor: 'context-menu',
                    }}
                    src={
                      <img
                        src={`http://localhost:8090/dyh/upload_images/user/${item.avatar}`}
                        alt=""
                      />
                    }
                  />
                ) : (
                  <Avatar
                    size={40}
                    style={{
                      margin: '0 8px',
                      background: `${qs.avatar}`,
                      cursor: 'context-menu',
                    }}
                    src={
                      <img
                        src={`http://localhost:8090/dyh/upload_images/business/${item.avatarSale}`}
                        alt=""
                      />
                    }
                  />
                )}
                <div>
                  <div className={styles.someInfor}>
                    {moment(Number(item.timeSaid)).format('YYYY-MM-DD HH:mm:ss')}&emsp;
                    {item.userTalking === '' ? business.salename : qs.nickname}
                  </div>
                  <div className={styles.rightRecording}>
                    <div
                      className={styles.talking}
                      style={{
                        background: item.userTalking === '' ? '#fff' : colorStr(2),
                      }}
                    >{`${item.userTalking === '' ? item.shopTalking : item.userTalking}`}</div>
                  </div>
                </div>
              </div>
            ))}
            <div id="box" />
          </div>

          <div className={styles.inputSend}>
            <TextArea
              maxLength={500}
              value={inputValue}
              onChange={onChange}
              placeholder={'请输入消息，按Enter键 或 点击发送按钮发送'}
              onPressEnter={(e) => {
                preventBubble(e);
                scrollToBottom();
                sendBtn();
              }}
              bordered={false}
              autoSize={{ minRows: 6, maxRows: 6 }}
              showCount
            />
            <Button style={{ backgroundColor: color }} className={styles.sendBtn} onClick={sendBtn}>
              发送
            </Button>
            <div className={styles.emoji}>
              <img
                src="https://gw.alicdn.com/imgextra/i2/O1CN01NMGMUe1G7qqwWm4Ud_!!6000000000576-55-tps-18-18.svg"
                alt={''}
                onClick={() => {
                  setEmojiModal(true);
                }}
              />
            </div>
          </div>
        </div>
        {qs.role === '1' ? (
          <div className={styles.store}>
            <div
              className={styles.storeImg}
              style={{
                cursor: 'context-menu',
              }}
            >
              <Avatar
                size={80}
                shape="square"
                style={{
                  margin: '0 8px',
                  background: `${qs.avatar}`,
                  cursor: 'context-menu',
                }}
                src={
                  <img
                    src={`http://localhost:8090/dyh/upload_images/business/${business.saleLogo}`}
                    alt=""
                  />
                }
              />
            </div>
            <div>
              <div style={{ margin: '10px 16px' }}>{business.saleName}</div>
              <div
                className={styles.enterShop}
                style={{
                  border: `1px solid ${color} `,
                  color: color,
                }}
                onClick={() => {
                  history.push({
                    pathname: '/saleone',
                    query: { ...business, lastRoute: '商品详情' },
                  });
                }}
              >
                进入店铺
              </div>
            </div>
          </div>
        ) : qs.role === '2' ? (
          <div className={styles.store}>买家地址：</div>
        ) : (
          ''
        )}
      </div>
    </Modal>
  );
};

export default Conversation;
